<template>
  <!-- 设置页面 -->
  <div class="page-setting tab-bar-page">
    <topBar :tab-title="getLanguageText('设置', AppSetting.language)" />
    <view class="page-nav">
      <flex class="page-label">{{getLanguageText('用户信息', AppSetting.language)}}</flex>
      <!-- 用户名称 -->
      <flex class="uni-form-item uni-column" justify="space-between">
        <view class="uni-label">{{ getLanguageText('用户名称', AppSetting.language) }}: </view>
        <input class="uni-input" v-model="AppSetting.userName" placeholder="请输入用户名称" maxlength="15" v-if="userInfoEdit" />
        <view class="uni-input-text" v-else>{{ AppSetting.userName }}</view>
      </flex>
      <!-- 产品名称 -->
      <flex class="uni-form-item uni-column" justify="space-between">
        <view class="uni-label">{{ getLanguageText('产品名称', AppSetting.language) }}: </view>
        <input class="uni-input" v-model="AppSetting.appName" placeholder="请输入产品名称" maxlength="15" v-if="userInfoEdit" />
        <view class="uni-input-text" v-else>{{ AppSetting.appName }}</view>
      </flex>
      <!-- 订单前缀 -->
      <flex class="uni-form-item uni-column" justify="space-between">
        <view class="uni-label">{{ getLanguageText('订单前缀', AppSetting.language) }}: </view>
        <input class="uni-input" v-model="AppSetting.orderPr" placeholder="请输入产品名称" maxlength="15" v-if="userInfoEdit" />
        <view class="uni-input-text" v-else>{{ AppSetting.orderPr || '未设置' }}</view>
      </flex>
      <!-- 小票抬头信息 -->
      <flex class="uni-form-item uni-column" justify="space-between">
        <view class="uni-label">{{ getLanguageText('小票抬头信息', AppSetting.language) }}: </view>
        <input class="uni-input" v-model="AppSetting.receiptTitle" placeholder="请输入小票抬头信息" maxlength="15" v-if="userInfoEdit" />
        <view class="uni-input-text" v-else>{{ AppSetting.receiptTitle || '未设置' }}</view>
      </flex>
      <flex class="uni-form-item uni-column" justify="flex-end">
        <button v-if="!userInfoEdit" style="margin: 0;" type="primary" size="mini" @click="userInfoEdit = !userInfoEdit">{{ getLanguageText('修改用户信息', AppSetting.language) }}</button>
        <template v-if="userInfoEdit">
          <button style="margin: 0 0.6rem 0 0;" size="mini" @click="userInfoEdit = !userInfoEdit">
            {{ getLanguageText('取消', AppSetting.language) }}
          </button>
          <button style="margin: 0;" type="primary" size="mini" @click="myClick('保存用户信息')">
            {{ getLanguageText('保存', AppSetting.language) }}
          </button>
        </template>
      </flex>
    </view>
    <view class="page-nav">
      <flex class="page-label">
        {{ getLanguageText('水位', AppSetting.language) }}
      </flex>
      <!-- 当前期数 -->
      <flex class="uni-form-item uni-column" justify="space-between">
        <view class="uni-label">{{ getLanguageText('当前期数', AppSetting.language) }}: </view>
        <view class="uni-input-text">第{{ AppSetting.periodsNum }}期</view>
      </flex>
      <!-- 佣金比例 -->
      <flex class="uni-form-item uni-column" justify="space-between">
        <view class="uni-label">{{ getLanguageText('佣金比例', AppSetting.language) }}: </view>
        <input class="uni-input" type="number" v-model="OrderSetting.commissionRate" placeholder="请输入佣金比例" v-if="orderSettingEdit" />
        <view class="uni-input-text" v-else>{{ OrderSetting.commissionRate || '未设置' }}</view>
      </flex>
      <!-- 大标节数限制 -->
      <flex class="uni-form-item uni-column" justify="space-between">
        <view class="uni-label">{{ getLanguageText('大标节数限制', AppSetting.language) }}: </view>
        <input class="uni-input" type="number" v-model="OrderSetting.quantityMaxNum_1" placeholder="请输入大标节数限制" v-if="orderSettingEdit" />
        <view class="uni-input-text" v-else>{{ OrderSetting.quantityMaxNum_1 || '未设置' }}</view>
      </flex>
      <!-- 小标节数限制 -->
      <flex class="uni-form-item uni-column" justify="space-between">
        <view class="uni-label">{{ getLanguageText('小标节数限制', AppSetting.language) }}: </view>
        <input class="uni-input" type="number" v-model="OrderSetting.quantityMaxNum_2" placeholder="请输入小标节数限制" v-if="orderSettingEdit" />
        <view class="uni-input-text" v-else>{{ OrderSetting.quantityMaxNum_2 || '未设置' }}</view>
      </flex>
      <!-- 大标单价 -->
      <flex class="uni-form-item uni-column" justify="space-between">
        <view class="uni-label">{{ getLanguageText('大标节数单价', AppSetting.language) }}: </view>
        <input class="uni-input" type="number" v-model="OrderSetting.quantityPrice_1" placeholder="请输入大标节数单价" v-if="orderSettingEdit" />
        <view class="uni-input-text" v-else>{{ `￥${OrderSetting.quantityPrice_1}` || '未设置' }}</view>
      </flex>
      <!-- 小标单价 -->
      <flex class="uni-form-item uni-column" justify="space-between">
        <view class="uni-label">{{ getLanguageText('小标节数单价', AppSetting.language) }}: </view>
        <input class="uni-input" type="number" v-model="OrderSetting.quantityPrice_2" placeholder="请输入小标节数单价" v-if="orderSettingEdit" />
        <view class="uni-input-text" v-else>{{ `￥${OrderSetting.quantityPrice_2}` || '未设置' }}</view>
      </flex>
      <!-- 修改水位信息 -->
      <flex class="uni-form-item uni-column" justify="flex-end">
        <button v-if="!orderSettingEdit" style="margin: 0;" type="primary" size="mini" @click="orderSettingEdit = !orderSettingEdit">
          {{ getLanguageText('修改水位信息', AppSetting.language) }}
        </button>
        <template v-if="orderSettingEdit">
          <button style="margin: 0 0.6rem 0 0;" size="mini" @click="orderSettingEdit = !orderSettingEdit">取消</button>
          <button style="margin: 0;" type="primary" size="mini" @click="myClick('修改水位信息')">
            {{ getLanguageText('保存', AppSetting.language) }}
          </button>
        </template>
      </flex>
    </view>
    <view class="page-nav">
      <view class="page-label">{{ getLanguageText('中奖录入', AppSetting.language) }}</view>
      <!-- 第一组 -->
      <flex class="uni-form-item uni-column" justify="space-between">
        <view class="uni-label">{{ getLanguageText('第一组', AppSetting.language) }}: </view>
        <input class="uni-input" type="number" maxlength="4" v-model="winningNum_1" placeholder="请输入第一组号码" v-if="winningEdit" />
        <view class="uni-input-text" v-else>{{ winningNum_1 || '未设置' }}</view>
      </flex>
      <!-- 第二组 -->
      <flex class="uni-form-item uni-column" justify="space-between">
        <view class="uni-label">{{ getLanguageText('第二组', AppSetting.language) }}: </view>
        <input class="uni-input" type="number" maxlength="4" v-model="winningNum_2" placeholder="请输入第一组号码" v-if="winningEdit" />
        <view class="uni-input-text" v-else>{{ winningNum_2 || '未设置' }}</view>
      </flex>
      <!-- 第三组 -->
      <flex class="uni-form-item uni-column" justify="space-between">
        <view class="uni-label">{{ getLanguageText('第三组', AppSetting.language) }}: </view>
        <input class="uni-input" type="number" maxlength="4" v-model="winningNum_3" placeholder="请输入第一组号码" v-if="winningEdit" />
        <view class="uni-input-text" v-else>{{ winningNum_3 || '未设置' }}</view>
      </flex>
      <flex class="uni-form-item uni-column" justify="flex-end">
        <button v-if="!winningEdit" style="margin: 0;" type="primary" size="mini" @click="winningEdit = !winningEdit">
          {{ getLanguageText('录入中奖信息', AppSetting.language) }}
        </button>
        <template v-if="winningEdit">
          <button style="margin: 0 0.6rem 0 0;" size="mini" @click="winningEdit = !winningEdit">{{ getLanguageText('取消', AppSetting.language) }}</button>
          <button style="margin: 0;" type="primary" size="mini" @click="myClick('录入中奖信息')">{{ getLanguageText('保存', AppSetting.language) }}</button>
        </template>
      </flex>
    </view>
    <view class="page-nav">
      <view class="page-label">
        {{ getLanguageText('开奖', AppSetting.language) }}（当前期数：等{{AppSetting.periodsNum}}期）
      </view>
      <!-- 开奖日期 -->
      <flex class="uni-form-item uni-column" justify="space-between">
        <view class="uni-label">{{ getLanguageText('开奖日期', AppSetting.language) }}: </view>
        <uni-datetime-picker type="datetime" v-model="OrderSetting.drawingDate" v-if="drawingDateEdit" />
        <view class="uni-input-text" v-else>
          {{ OrderSetting.drawingDate || '未设置' }}
        </view>
      </flex>
      <flex class="uni-form-item uni-column" justify="flex-end">
        <template v-if="!drawingDateEdit">
          <button 
            style="margin: 0 0.5rem 0 0;" 
            size="mini" 
            @click="drawingDateEdit = true"
          >
            {{ getLanguageText('设置开奖日期', AppSetting.language) }}
          </button>
          <button 
            style="margin: 0;" 
            type="primary" 
            size="mini" 
            @click="myClick('立即开奖')"
          >
            {{ getLanguageText('立即开奖', AppSetting.language) }}
          </button>
        </template>
        <template v-else>
          <button style="margin: 0 0.6rem 0 0;" size="mini" @click="drawingDateEdit = !drawingDateEdit">{{ getLanguageText('取消', AppSetting.language) }}</button>
          <button 
            style="margin: 0;" 
            type="primary" 
            size="mini" 
            @click="myClick('设置开奖日期')"
          >
            {{ getLanguageText('保存', AppSetting.language) }}
          </button>
        </template>
      </flex>
    </view>
    <view class="page-nav">
      <view class="page-label">{{ getLanguageText('设置', AppSetting.language) }}</view>
      <flex class="uni-form-item uni-column" justify="space-between">
        <view class="uni-label">{{ getLanguageText('语言', AppSetting.language) }}: </view>
        <template v-if="!baseSettingEdit">
          <view class="uni-input-text">
            {{  AppSetting.language == 1 ? getLanguageText('中文', AppSetting.language) : getLanguageText('西班牙语', AppSetting.language)  }}
          </view>
        </template>
        <uni-data-checkbox 
          v-model="AppSetting.language"
          :localdata="languageLocalData"
          v-if="baseSettingEdit"
        >
        </uni-data-checkbox>
      </flex>
      <flex class="uni-form-item uni-column" justify="flex-end">
        <template v-if="baseSettingEdit">
          <button style="margin: 0 0.6rem 0 0;" size="mini" @click="baseSettingEdit = !baseSettingEdit">{{ getLanguageText('取消', AppSetting.language) }}</button>
          <button 
            style="margin: 0;" 
            type="primary" 
            size="mini" 
            @click="myClick('保存基础设置')"
          >
            {{ getLanguageText('保存基础设置', AppSetting.language) }}
          </button>
        </template>
        <template v-else>
          <button 
            style="margin: 0;" 
            type="primary" 
            size="mini" 
            @click="baseSettingEdit = !baseSettingEdit"
          >
            {{ getLanguageText('修改设置', AppSetting.language) }}
          </button>
        </template>
      </flex>
    </view>
    <view class="page-nav">
      <view class="page-label">开发设置</view>
      <flex class="uni-form-item uni-column" justify="space-between">
        <view class="uni-label">数据初始化: </view>
        <button 
          style="margin: 0;" 
          type="primary" 
          size="mini" 
          @click="myClick('数据初始化')"
        >
          清空当前数据
        </button>
      </flex>
    </view>
    <comTabBar label="设置" />
  </div>
</template>
<script>
import { 
  getAppSetting,
  getOrderSetting,
  setStorage,
  getOrderList,
  // setOrderSetting,
  setOrderStatistics,
  storageInit
} from '../../utils/appStorage'
import {  getLanguageText } from '../../utils/language'

export default {
  name: "Setting",
  data() {
    return {
      periods: 1,
      userInfoEdit: false,
      orderSettingEdit: false,
      winningEdit: false,
      drawingDateEdit: false,
      baseSettingEdit: false,
      AppSetting: {},
      OrderSetting: {},
      winningNum_1: '',
      winningNum_2: '',
      winningNum_3: '',
      languageLocalData: [
        {
          text: '中文',
          value: 1
        }, {
          text: '西班牙语',
          value: 2
        }
      ],
      OrderList: []
    };
  },
  components: {},
  onLoad() {
    this.init()
  },
  computed: {
		// 根据订单列表动态计算订单总金额
		orederAmount() {
			let data = 0
			for (let i = 0; i < this.OrderList.length; i++) {
				let item = this.OrderList[i]
				data += item.quantity * (item.orderNum.length == 4 ? this.OrderSetting.quantityPrice_1 : this.OrderSetting.quantityPrice_2)
			}
			return data
		}
  },
  methods: {
    init() {
      getAppSetting(data => {this.AppSetting = data})
      getOrderSetting(data => {
        this.OrderSetting = data
        if (data.winningNumber && data.winningNumber.length > 0) {
          this.winningNum_1 = data.winningNumber[0]
          this.winningNum_2 = data.winningNumber[1]
          this.winningNum_3 = data.winningNumber[2]
        }
      })
    },
    getLanguageText,
    msg(type, messageText) {
      this.msgType = type
      this.messageText = messageText
      this.$refs.message.open()
    },
    myClick(type, data) {
      switch (type) {
        case '数据初始化':
          uni.showModal({
            title: "确定初始化数据？",
            content: "（初始化后将丢失当前数据）",
            confirmText: "确定",
            confirmColor: "#007aff",
            cancelText: "取消",
            cancelColor: "#007aff",
            success: (res) => {
              if (!res.confirm) return
              storageInit()
              uni.showToast({title: "初始化完成", icon: 'success'})
              setTimeout(() => {
                // uni.redirectTo({ url: '/pages/setting/setting' })
                this.init()
              }, 500)
            }
          })
          break;
        case '保存用户信息':
        case '保存基础设置':
          uni.setStorage({
            key: 'AppSetting',
            data: this.AppSetting,
            success: () => {
              this.userInfoEdit = false
              this.baseSettingEdit = false
              uni.showToast({title: "保存成功", icon: 'success'})
              setTimeout(() => {
                // uni.redirectTo({ url: '/pages/setting/setting' })
                this.init()
              }, 500)
            },
            fail: (err) => {
              uni.showToast({title: "保存失败", icon: 'error'})
            }
          })
          break;
        case '修改水位信息':
        case '录入中奖信息':
        case '设置开奖日期':
          console.log('this.OrderSetting---', this.OrderSetting)
          if (
            type == '录入中奖信息'
          ) {
            if (
              !this.winningNum_1 ||
              !this.winningNum_2 ||
              !this.winningNum_3
            ) {
              uni.showToast({title: "请录入中奖号码", icon: 'error'})
              return
            }
            this.OrderSetting.winningNumber = [
              this.winningNum_1, this.winningNum_2, this.winningNum_3
            ]
          }
          uni.setStorage({
            key: 'OrderSetting',
            data: this.OrderSetting,
            success: () => {
              this.orderSettingEdit = false
              this.winningEdit = false
              uni.showToast({title: "保存成功", icon: 'success'})
              setTimeout(() => {
                // uni.redirectTo({ url: '/pages/setting/setting' })
                this.init()
              }, 500)
            },
            fail: (err) => {
              uni.showToast({title: "修改失败", icon: 'error'})
            }
          })
          break;
        case '立即开奖':
          let that = this
          if (
            !this.winningNum_1 ||
            !this.winningNum_2 ||
            !this.winningNum_3
          ) {
            uni.showToast({title: "请录入中奖号码", icon: 'error'})
            return
          }
          uni.showModal({
            title: "确定现在开奖？",
            content: "（开奖后本期数据将不可再变动）",
            confirmText: "确定",
            confirmColor: "#007aff",
            cancelText: "取消",
            cancelColor: "#007aff",
            success: (res) => {
              if (res.confirm) {
                getOrderList(list => {
                  this.OrderList = list
                  if (!list || list.length == 0) {
                    uni.showModal({
                      title: '开奖失败',
                      content: '原因：当前期数还未有销售记录',
                      confirmText: "确定"
                    })
                    return
                  }
                  getOrderList(lists => {
                    // * 开奖更新历史数据
                    let OrderStatisticsNew = [{
                      orderList: list.map(item => {
                        return {
                          ...item,
                          money: item.quantity * (item.orderNum.length == 4 ? this.OrderSetting.quantityPrice_1 : this.OrderSetting.quantityPrice_2)
                        }
                      }),
                      orderLists: lists.map(item => {
                        return {
                          ...item,
                          orderNumTwo: item.orderNumTwo.map(v => {
                            return {
                              ...v,
                              money: v.quantity * (v.orderNum.length == 4 ? this.OrderSetting.quantityPrice_1 : this.OrderSetting.quantityPrice_2)
                            }
                          }),
                          orderNumFour: item.orderNumFour.map(v => {
                            return {
                              ...v,
                              money: v.quantity * (v.orderNum.length == 4 ? this.OrderSetting.quantityPrice_1 : this.OrderSetting.quantityPrice_2)
                            }
                          }),
                        }
                      }),
                      periodsNum: this.AppSetting.periodsNum,
                      orderPr: this.AppSetting.orderPr,
                      dateDrawing: new Date().getTime(),
                      orderAmount: this.orederAmount,
                      commissionRate: this.OrderSetting.commissionRate,
                      ...this.OrderSetting
                    }]
                    console.log('OrderStatisticsNew----', OrderStatisticsNew)
                    // return
                    setOrderStatistics(OrderStatisticsNew, (data) => {
                      // 期数 +1
                      uni.setStorage({ key: 'AppSetting', data: {
                        ...this.AppSetting,
                        periodsNum: this.AppSetting.periodsNum + 1
                      } })
                      // 初始化订单设置
                      uni.setStorage({ key: 'OrderSetting', data: {
                        ...this.OrderSetting,
                        periodsNum: this.OrderSetting.periodsNum + 1,
                        winningNumber: []
                      } })
                      // 清空订单
                      uni.setStorage({ key: 'OrderList', data: [] })
                      uni.setStorage({ key: 'OrderLists', data: [] })
                      uni.showToast({title: "开奖成功", icon: 'success'})
                      setTimeout(() => {
                        // uni.redirectTo({ url: '/pages/setting/setting' })
                        this.init()
                      }, 500)
                    })
                  }, 'OrderLists')
                })
              } else {
                console.log('取消')
              }
            }
          })
          break;
        default:
          break;
      }
    },
    bluetooth() {
      // uni.redirectTo({ url: '/pages/bluetooth/bluetooth' })

    }
  }
};
</script>
<style lang="scss" scoped>
.page-setting {
  .uni-input-text {
    width: 11rem;
  }
  .uni-input {
    width: 11rem;
  }
}
</style>
